import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Select,
  Cascader,
  Image,
  Row,
  Space,
  Switch,
  Popconfirm,
  message
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import Editor from '@/components/editor';
import { useCommon } from '@/hooks/common';
import { toYuan } from '@/utils/format-number';

import { ProductModal } from './modal';
import ComponentNamesModal from './components/ComponentNamesModal/ComponentNamesModal';
import { get } from 'lodash';


export default function ProductListPage() {
  const uri = 'pre-product';
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    onSwitch,
    onSwitchTop,
    cateList,
    doDel,
    onEdit,
    onSearch,
    handleChange,
    refetch
  } = useCommon(
    { name: '', groupId: [], disable: '' },
    uri,
    {
      name: '',
      id: 0,
      catalogueId1: '',
      catalogueId: '',
      disable: 1,
      sort: 1,
      price: 0,
      url: '',
      component: []
    },
    'product-catalogue',
  );
  const [info, setInfo] = useState<any>({});
  const [isEdit, setIsEdit] = useState(false);

  const [baseInfo, setBaseInfo] = useState<any>({});
  const { material, materialName, printType, supplier, suitFor, sizes, technology = [] } = baseInfo || {};
  const getInfo = async () => {
    commonService.getCustomApi('/common/baseProperty/getAllProperty', {}).then((res) => {
      console.log("baseInfo", res);
      setBaseInfo(res);
    });
  };

  useEffect(() => {
    getInfo();
  }, []);

  const onCreate = () => {
    commonService.addApi('pre-product', { size: '[]', component: '[]' }).then(() => {
      refetch();
    });
  };

  const onEditDetail = (row: any) => {
    setInfo(row);
    setIsEdit(true);
  };

  const save = () => {
    const { id, detail } = info;
    commonService.postCustomApi('/admin/pre-product/editDetail', { id, detail }).then(() => {
      message.success('修改成功');
      setIsEdit(false);
      refetch();
    });
  };

  const setContent = (e: any) => {
    setInfo({ ...info, detail: e });
  };


  const columns: ColumnsType<any> = [
    { title: '名称', dataIndex: 'name', width: 100 },
    { title: '分类名', dataIndex: 'groupName', width: 100 },
    {
      title: '缩略图',
      dataIndex: 'thumbs',
      width: 200,
      render: (thumbs) => (
        <div className="flex gap-[10px]">
          {JSON.parse(thumbs || '[]').map((item: string, index: number) => {
            return <Image key={index} preview className="!w-[80px]" src={item} />;
          })}
        </div>
      ),
    },
    { title: '面料', dataIndex: 'materialName', align: 'center', width: 80 },
    {
      title: '工艺',
      dataIndex: 'technology',
      align: 'center',
      width: 80,
      render: (fillType) => {
        const name = get((technology || []).find((item: any) => item.value === fillType), 'name', "--");
        return name;
      },
    },
    {
      title: '印刷',
      dataIndex: 'fillType',
      align: 'center',
      width: 80,
      render: (fillType) => (fillType === 0 ? '满版打印' : '局部打印'),
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center',
      width: 60,
      render: (val) => toYuan(val),
    },
    // { title: '排序', dataIndex: 'sort', align: 'center', width: 60 },
    {
      title: '置顶',
      dataIndex: 'isTop',
      align: 'center',
      width: 120,
      render: (isTop, record) => (
        <Switch checked={isTop === 0} onChange={() => onSwitchTop(record.id)} />
      ),
    },
    {
      title: '状态',
      dataIndex: 'disable',
      align: 'center',
      width: 120,
      render: (disable, record) => (
        <Switch checked={disable === 0} onChange={() => onSwitch(record.id)} />
      ),
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex flex-col gap-[10px] w-full justify-center text-gray">
          <Button onClick={() => onEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <Button danger>删除</Button>
          </Popconfirm>
          <Button type="primary" onClick={() => onEditDetail(record)}>详情编辑</Button>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      {!isEdit ?
        <><Card>
          <Form form={searchForm} onFinish={onSearch}>
            <Row gutter={[16, 16]}>
              <Col span={8} lg={6}>
                <Form.Item<any> label="分类" name="catalogueId" className="!mb-0">
                  <Cascader
                    showSearch
                    options={cateList}
                    fieldNames={{ label: 'name', value: 'id', children: 'sonList' }}
                  />
                </Form.Item>
              </Col>
              <Col span={8} lg={6}>
                <Form.Item<any> label="名称" name="name" className="!mb-0">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={8} lg={6}>
                <Form.Item<any> label="状态" name="disable" className="!mb-0">
                  <Select
                    options={[
                      { label: '全部', value: '' },
                      { label: '已上架', value: 0 },
                      { label: '已下架', value: 1 },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={24} lg={12}>
                <div className="flex justify-end">
                  <Button onClick={onSearchFormReset}>重置</Button>
                  <Button type="primary" htmlType="submit" className="ml-4">
                    查询
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

          <Card
            title="产品列表"
            extra={
              <div className="flex flex-row gap-[10px]">
                <Button type="primary" onClick={() => onCreate()}>
                  新增
                </Button>
                {/* 查看命名的配置弹窗 */}
                <ComponentNamesModal />
              </div>
            }
          >
            <Table
              rowKey="id"
              size="small"
              pagination={{ total: data.totalCount }}
              scroll={{ x: 'max-content' }}
              columns={columns}
              dataSource={data.list}
              rowSelection={{ ...rowSelection }}
              onChange={handleChange}
            />
          </Card></> : <Card><Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            layout="horizontal"
          >
            <Form.Item<any> label="标题" required>
              {info.name}
            </Form.Item>
            <Form.Item<any> label="内容" required>
              <Editor value={info.detail} onChange={setContent} />
            </Form.Item>
            <div className='flex gap-[10px]'>
              <Button type="primary" onClick={() => save()}>提交</Button>
              <Button onClick={() => setIsEdit(false)}>取消</Button>
            </div>

          </Form></Card>}
      <ProductModal {...ModalPros} cateList={cateList} />
    </Space>
  );
}
